from functools import wraps

from flask import jsonify, session, g
from flask.json import jsonify


def exception_catch(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            result = func(*args, **kwargs)
        except Exception as e:
            return jsonify({'code': 4000, 'error': str(e)})
        return result
    return wrapper


def login_require(func):
    def wrapper(*args, **kwargs):
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'code': 4000, 'message': '还未登陆'})
        else:
            g.user_id = user_id
            return func(*args, **kwargs)
    return wrapper


def json_resp(**kwargs):
    if kwargs.pop('code') != '200':
        # 记录日志
        pass
    return jsonify(kwargs)